<?php
declare (strict_types=1);
namespace app\controller\v2;

use app\model\Goods as GoodsM;
use app\model\Order as OrderM;
use app\model\Promotion;
use app\model\Supplier;
use app\model\Supplier as SupplierM;
use app\model\WsBusinessOrder;
use app\util\CacheHelper;
use app\util\MengChen;
use app\util\Yizun;
use think\annotation\route\Group;
use think\annotation\Route;
use think\facade\Db;
use function GuzzleHttp\Promise\exception_for;

/**
 * 订单
 * Class Order
 * @package app\controller\v1
 *@Group("v2/Order")
 */
class Order
{
    /**
     * 获取地区
     * @Route("getAreas", method="POST")
     */
    public function getAreas()
    {
        //$data['appId'] = input('post.appId', '', 'int');
        $data['pid'] = input('post.pid', '', 'int');
        //$data['productId'] = input('post.productId', '', 'int');
        $data['timestamp'] = time();
        if (empty( $data['timestamp'])) {
            return json_error(10001);
        }

        //$mengM = new MengChen($data['appId'], $data['timestamp']);
        $mengM = new MengChen();
        $res = $mengM->getAreas($data);

        return json_ok($res, 200);

    }


    /**
     * 购买订单
     * @Route("purchase", method="POST")
     */
    public function purchase()
    {
        $supplierId = input('post.supplierId', 5, 'string');
        $trackingCode= input('post.trackingCode', '', 'string');
        //$date['appId'] = input('post.appId', '', 'int');
        $date['address']= input('post.address', '', 'string');
        $date['cardNumber'] = input('post.cardNumber', '', 'string');
        $date['city'] = input('post.city', '', 'string');
        $date['country'] = input('post.country', '', 'string');
        $date['idCard'] = input('post.idCard', '', 'string');
        $date['mobile'] = input('post.mobile', '', 'string');
        $date['province'] = input('post.province', '', 'string');
        //$date['productId'] = input('post.productId', '', 'int');
        $date['realName'] = input('post.realName', '', 'string');
        //$date['timestamp'] = time();

        $oneSupplier = (new SupplierM())->where('id', $supplierId)->find();
        if (empty($oneSupplier)) {
            return json_error(10001);
        }

        //生成订单号
        $redis = new CacheHelper();
        $key = 'distribution:order_no:' . time();
        $currentCount = $redis->incr($key);
        $redis->expire($key, 300);
        $base = intval(config('cachekeys.order_base') ?? 0);
        $suffix = sprintf("%05d", $base + ($currentCount ?: 99));
        $orderNo = date('Ymd') . substr($key, -5) . $suffix;
        $date['agentOrderCode'] = 'MC'.$orderNo;
        $tradeCode = base64_decode($trackingCode);
        $tradeCodeArr = explode(':', $tradeCode);

        $mengChen = new MengChen();
        $res = $mengChen->purchase($date);
        //根据跟踪码获取佣金信息
        $reward = (new Promotion())->where('goods_id',(int)$tradeCodeArr[1])->where('user_id', $tradeCodeArr[3])->find();
        if (empty($reward)) {
            return json_error(10004);
        }

        $oneGoods = (new GoodsM())->where('goods_id', $tradeCodeArr[1])->find();

        if (empty($oneGoods)) {
            return json_error(10004);
        }

        //根据promotion_id查询一级和二级分销商
        $promotion = (new Promotion())->where('user_id',$tradeCodeArr[3])->find();
        //dump($promotion);die;

        $orderData = [
            'supplier_id' => $supplierId,
            'third_goods_id' =>  '',
            'goods_id' => $tradeCodeArr[1],
            'promotion_id' => $tradeCodeArr[3],
            'promotion_pid' => $promotion['parent_user_id'],
            //'merchant_id' => $date['appId'],
            'merchant_id' => MengChen::APP_ID,
            'user_name' => $date['realName'] ?? '',
            'contact_phone' => $date['mobile'] ?? '',
            'card_number' => $date['idCard'],
            'address' => $date['province'] . $date['city'] . $date['country'] . $date['address'],
            'order_no' => $orderNo,
            'source_trade_id' =>  $date['agentOrderCode'],
            'buy_phone' => $date['cardNumber'] ?? '',
            //'trade_id' => $res['data']['tradeId'] ?? '',
            //'goods_title' => $res['data']['goods_name'] ?? '',
            'status' => $res['code'] ? \app\model\Order::ORDER_STATUS_FILLING : \app\model\Order::ORDER_STATUS_COMMIT,
            'tracking_code' => $trackingCode,
            'active_brokerage' => $reward['active_brokerage']??0,
            'charge_brokerage' => $reward['charge_brokerage']??0,
            'goods_type' => MengChen::GOODS_TYPE_ID
        ];

        $orderM = new \app\model\Order();
        $orderM->save($orderData);
        $res['orderNo'] = $orderNo;
        if ($res['code']) {
            return json_error($res['code'], $res['message']??'', $orderNo);
        }
        $reportKey = config('cachekeys.user_report');
        $jsonData = array(
            'trackCode' => $trackingCode,// 跟踪号
            'goodsType' => $orderData['goods_type'], // 商品类型
            'orderTotalNum' => 1, // 订单总数
            'yjMoney' => 0, // 佣金金额
        );
        $redis->lpush($reportKey, json_encode($jsonData));
        return json_ok([$res], 200);
    }


    /**
     * 提交订单
     * @Route("commit", method="POST")
     */
    public function commit()
    {
        //$merchantId = input('post.merchantId', '', 'string');
        $supplierId = input('post.supplierId', 1, 'string');
        $buyer = input('post.buyer', '', 'string');
        $merchantNick = input('post.merchantNick', 'RRpartner', 'string');
        $tradeAddress = input('post.tradeAddress', '', 'string');
        $transactor = input('post.transactor', '', 'string');
        $tradeGoods = input('post.tradeGoods', '', 'string');
        $tradeExp = input('post.tradeExp', '', 'string');
        $version = input('post.version', '3.0', 'string');
        $messageFormat = input('post.messageFormat', 'json', 'string');
        $locale = input('post.locale', 'zh_CN', 'string');
        $source = input('post.source', '150', 'string');
        $tradeType = input('post.tradeType', '11', 'string');
        $trackingCode= input('post.trackingCode', '', 'string');
        $method = 'tradeService.addTrade';
        $oneSupplier = (new SupplierM())->where('id', $supplierId)->find();
        if (empty($oneSupplier)) {
            return json_error(10001);
        }
        $merchantId = $oneSupplier['merchant_id'];

        $redis = new CacheHelper();
        if (!$redis->lock("commit:$buyer",1)) {
            return json_error(10017);
        }

        //生成订单号
        $redis = new CacheHelper();
        $key = 'distribution:order_no:' . time();
        $currentCount = $redis->incr($key);
        $redis->expire($key, 300);
        $base = intval(config('cachekeys.order_base') ?? 0);
        $suffix = sprintf("%05d", $base + ($currentCount ?: 99));
        $orderNo = date('Ymd') . substr($key, -5) . $suffix;
        $sourceTradeId = 'CDS'.$orderNo;

        $tradeCode = base64_decode($trackingCode);
        $tradeCodeArr = explode(':', $tradeCode);

        $params = [
            //'merchantId' => $tradeCodeArr[3],
            'merchantId' => $merchantId,
            'buyer' => $buyer,
            'sourceTradeId' => $sourceTradeId,
            'merchantNick' => $merchantNick,
            'tradeAddress' => stripslashes(htmlspecialchars_decode($tradeAddress)),
            'transactor' => stripslashes(htmlspecialchars_decode($transactor)),
            'tradeGoods' => stripslashes(htmlspecialchars_decode($tradeGoods)),
            'tradeExp' => stripslashes(htmlspecialchars_decode($tradeExp)),
            'version' => $version,
            'source' => $source,
            'tradeType' => $tradeType,
            'trackingCode' => $trackingCode,
        ];

        $yizun = new Yizun($method, $messageFormat, $locale, $version);
        $res = $yizun->addTrade($params);

        $transactorInfo = json_decode(stripslashes(htmlspecialchars_decode($transactor)), true);
        $addressInfo = json_decode(stripslashes(htmlspecialchars_decode($tradeAddress)), true);
        $tradeGoodsInfo = json_decode(stripslashes(htmlspecialchars_decode($tradeGoods)), true);
        $address = $addressInfo['province'] . $addressInfo['city'] . $addressInfo['country'] . $addressInfo['receiveAdd'];

        //根据跟踪码获取佣金信息
        $reward = (new Promotion())->where('goods_id',(int)$tradeCodeArr[1])->where('user_id', $tradeCodeArr[3])->find();
        if (empty($reward)) {
            return json_error(10004);
        }

        $oneGoods = (new GoodsM())->where('goods_id', $tradeCodeArr[1])->find();

        if (empty($oneGoods)) {
            return json_error(10004);
        }

        //根据promotion_id查询一级和二级分销商
        $promotion = (new Promotion())->where('user_id',$tradeCodeArr[3])->find();

        $orderData = [
            'supplier_id' => $oneGoods['supplier_id'],
            'third_goods_id' => $tradeGoodsInfo['opTradeGoodsList'][0]['goodsId'] ?? '',
            'goods_id' => $tradeCodeArr[1],
            'promotion_id' => $tradeCodeArr[3],
            'promotion_pid' => $promotion['parent_user_id'],
            'merchant_id' => $merchantId,
            'user_name' => $transactorInfo['transactorName'] ?? '',
            'contact_phone' => $addressInfo['telPhone'] ?? '',
            'card_number' => $transactorInfo['credentId'] ?? '',
            'address' => $address,
            'order_no' => $orderNo,
            'source_trade_id' => $sourceTradeId,
            'buy_phone' => $tradeGoodsInfo['opTradeGoodsList'][0]['phoneNum'] ?? '',
            'trade_id' => $res['data']['tradeId'] ?? '',
            'goods_title' => $res['data']['goods_name'] ?? '',
            'goods_type' => $tradeGoodsInfo['opTradeGoodsList'][0]['goodsTypeId'] ?? '',
            'status' => $res['code'] ? \app\model\Order::ORDER_STATUS_FILLING : \app\model\Order::ORDER_STATUS_COMMIT,
            'tracking_code' => $trackingCode,
            'active_brokerage' => $reward['active_brokerage'],
            'charge_brokerage' => $reward['charge_brokerage'],
        ];

        $orderM = new \app\model\Order();
        $orderM->save($orderData);

        if ($res['code']) {
            return json_error($res['code'], $res['message']);
        }
        $reportKey = config('cachekeys.user_report');
        $jsonData = array(
            'trackCode' => $trackingCode,// 跟踪号
            'goodsType' => $orderData['goods_type'], // 商品类型
            'orderTotalNum' => 1, // 订单总数
            'yjMoney' => 0, // 佣金金额
        );
        $redis->lpush($reportKey, json_encode($jsonData));

        return json_ok([$res], 200);
    }

    /**
     * 选择号码接口
     * @Route("productList", method="POST")
     */
    public function productList()
    {
        $data['appId'] = input('post.appId', '', 'int');
        $data['isp'] = input('post.isp', '', 'int');
        $data['start'] = input('post.start', 0, 'int');
        $data['limit'] = input('post.limit', 1000, 'int');
        $data['timestamp'] = time();
        if (empty($data['appId'])) {
            return json_error(10001);
        }

        $mengM = new MengChen($data['appId'], $data['timestamp']);
        $res = $mengM->productList($data);

        return json_ok([$res], 200);

    }


    /**
     * 选择号码接口
     * @Route("selectNum", method="POST")
     */
    public function selectPhoneNum()
    {
        $supplierName = input('post.mengchen', 'mengchen', 'string');

        switch ($supplierName) {
            case 'yizun':
                $goodsId = input('post.goodsId', '', 'int');
                $cityCode = input('post.cityCode', '', 'string');
                $provinceCode = input('post.provinceCode', '', 'string');
                $amounts = input('post.amounts', '20', 'int');
                $searchValue = input('post.searchValue', '', 'string');
                $version = input('post.version', '1.0', 'string');
                $messageFormat = input('post.messageFormat', 'json', 'string');
                $locale = input('post.locale', 'zh_CN', 'string');
                $method = 'goodsService.blocCUSelectNUmberOnline';

                $data['appId'] = input('post.appId', '', 'int');
                $data['pid'] = input('post.pid', '', 'int');
                $data['productId'] = input('post.productId', '', 'int');
                $data['timestamp'] = time();

                $params = [
                    'goodsId' => $goodsId,
                    'cityCode' => $cityCode,
                    'provinceCode' => $provinceCode,
                    'amounts' => $amounts,
                    'searchValue' => $searchValue,
                ];

                $modelM = new Yizun($method, $messageFormat, $locale, $version);
                break;
            case 'mengchen':
                $params['city'] = input('post.city', '', 'string');
                $params['province'] = input('post.province', '', 'string');
                //$params['appId'] = input('post.appId', '', 'int');
                $params['productId'] = input('post.productId', '', 'int');
                $params['searchValue'] = input('post.searchValue', '', 'string');
                //$params['timestamp'] = time();
                $modelM = new MengChen();
                break;
        }

        $res = $modelM->selectPhoneNum($params);

        if ($res['code']) {
            return json_error($res['code'], $res['message']);
        }

        return json_ok($res, 200);

    }


    /**
     * 验证号码是否被占用
     * @Route("isOccupy", method="POST")
     */
     public function isOccupy()
     {
         $serialNumber = input('post.serialNumber', '', 'string');
         $cityCode = input('post.cityCode', '', 'string');
         $provinceCode = input('post.provinceCode', '', 'string');
         $certCode = input('post.certCode', '', 'string');
         $version = input('post.version', '1.0', 'string');
         $messageFormat = input('post.messageFormat', 'json', 'string');
         $locale = input('post.locale', 'zh_CN', 'string');
         $method = 'goodsService.blocCUOnlineOccupyNUmber';

         $params = [
             'serialNumber' => $serialNumber,
             'cityCode' => $cityCode,
             'provinceCode' => $provinceCode,
             'certCode' => $certCode,
         ];

         $yizun = new Yizun($method, $messageFormat, $locale, $version);
         $res = $yizun->isOccupy($params);
         if ($res['code']) {
             return json_error($res['code'], $res['message']);
         }

         return json_ok([], 200);

     }


    /**
     * 验证身份接口
     * @Route("validate", method="POST")
     */
    public function validateIdentity()
    {
        $identiyData = input('post.params', '', 'string');
        $chanId = input('post.chanId', '', 'string');
        $version = input('post.version', '2.0', 'string');
        $messageFormat = input('post.messageFormat', 'json', 'string');
        $locale = input('post.locale', 'zh_CN', 'string');
        $method = 'ltService.identityCheck';

        $params = [
            'params' => $identiyData,
            'chanId' => $chanId,
        ];

        $yizun = new Yizun($method, $messageFormat, $locale, $version);
        $res = $yizun->validate($params);
        if ($res['code']) {
            return json_error($res['code'], $res['message']);
        }

        return json_ok([], 200);

    }


    /**
     * 查询订单接口
     * @Route("query", method="POST")
     */
    function query()
    {
        //$merchantId = input('post.merchantId', 194502, 'int');
        $tradeId = input('post.tradeId', '', 'int');
        $order = (new OrderM)->where('trade_id', $tradeId)->find();
        if (empty($order)) {
            return json_error(10001);
        }
        $merchantId = $order['merchant_id'];

        $version = '1.0';
        $locale = 'zh_CN';
        $messageFormat = 'json';
        $method = 'tradeService.queryOrderLogistics';
        $YizunM = new Yizun($method, $messageFormat, $locale, $version);

        $params = json_encode([
            'data' => [[
                'merchantId' => $merchantId,
                'tradeId' => $tradeId,
            ]]
        ]);

        $res = $YizunM->query($params);
        if ($res['code']) {
            return json_error($res['code'], $res['message']);
        }

        return json_ok($res, 200);
    }

    /**
     * 订单详情
     * @Route("detail", method="POST")
     */
    public function detail()
    {
        //$data['appId'] = input('post.appId', '', 'int');
        $data['agentOrderCode'] = input('post.agentOrderCode', '', 'string');
        //$data['productId'] = input('post.productId', '', 'int');
        //$data['timestamp'] = time();
        if ( empty( $data['agentOrderCode'])) {
            return json_error(10001);
        }
        $data['agentOrderCode'] = 'MC'.$data['agentOrderCode'];
        $mengM = new MengChen();
        $res = $mengM->query($data);

        return json_ok($res, 200);

    }

    /**
     * 查询订单接口
     * @Route("open_list", method="GET")
     */
    public function getOrderList()
    {
        $trackingCode = input('get.trackingCode', '', 'string');
        $tradeStatus = input('get.tradeStatus', '', 'string');
        $startTime = input('get.startTime', '', 'string');
        $endTime = input('get.endTime', '', 'string');
        $limit = input('get.count', 100000, 'int');
        $tradeCode = base64_decode($trackingCode);
        $tradeCodeArr = explode(':', $tradeCode);

        if (empty($tradeCodeArr[1])) {
            return json_error(10001);
        }

        //根据商品id查询运营商
        $supplier_id = (new \app\model\Goods())->where('goods_id', $tradeCodeArr[1])->value('supplier_id');
        if (empty($supplier_id)) {
            return json_error(10001);
        }

        $where[] = ['tracking_code', '=', $trackingCode];
        if ($tradeStatus == 2) {
            $where[] = ['active_status', '=', 1];
        }

        if ($tradeStatus == 3) {
            $where[] = ['charge_status', '=', 1];
        }

        if (!empty($startTime)) {
            $where[] = ['create_time', '>', strtotime($startTime)];
        }

        if (!empty($endTime)) {
            $where[] = ['create_time', '<', strtotime($endTime)];
        }

        $redis = new CacheHelper();
        $ignores = $redis->smembers('ignore:tradeId:');
        if (!empty($ignores)) {
            $where[] = ['trade_id', 'not in', $ignores];
        }

        $list = Db::name(OrderM::$_table)->where($where)
            ->field(['supplier_id','user_name','contact_phone','trade_id','buy_phone','source_trade_id','active_status','charge_status','create_time'])
            ->limit($limit)
            ->select();

        return json_ok($list, 200);
    }

    /**
     * 查询订单接口
     * @Route("ignore", method="GET")
     */
    public function ignoreOrder()
    {
        $tradeIds = input('get.tradeIds', '', 'string');
        if (empty($tradeIds)) {
            return json_error(10001);
        }
        $tradeArr = explode(',', $tradeIds);
        $redis = new CacheHelper();
        foreach ($tradeArr as $tradeId) {
            $redis->sadd('ignore:tradeId:', $tradeId);
        }

        return json_ok([], 200);
    }



}
